#!/usr/bin/python
#coding:utf-8
'''
日志工具类
time：2019-11-12
author：wangzonghui
打印包含报错方法：log.error("自定义信息",exc_info = True)
'''
#!/usr/bin/python
#coding:utf-8

import logging,os,sys
import logging.handlers


def script_path():
    '''
    获取项目目录
    '''
    path = os.path.realpath(sys.argv[0])
    if os.path.isfile(path):
        path = os.path.dirname(path)
    return os.path.abspath(path)

#创建日志目录
log_path = os.path.join(script_path(),'logs')
if not os.path.exists(log_path):
    os.makedirs(log_path)

#日志内容格式
message_format  = '%(asctime)s %(levelname)s %(pathname)s(line:%(lineno)d) %(message)s'



def getLog(filename="my-all.log"):
    '''
    获取日志
    filename：日志文件名，默认my.log，文件不自动分隔
    '''
    log_file = os.path.join(log_path,filename)
    logging.basicConfig(level=logging.DEBUG,format=message_format)

    log=logging.getLogger(filename)

    if not log.handlers:  #避免重复加载handler
        file= logging.FileHandler(log_file,encoding='utf-8')
        file.setFormatter(logging.Formatter(message_format))
        log.addHandler(file)

    return log

def getDayLog(filename="my-day.log",when="MIDNIGHT",backupCount=30):
    '''
    获取日志对象，24小时拆分一次

    filename:日志文件名，默认my.log
    when：间隔多久拆分一次，默认MIDNIGHT，每天过0点执行，可填写：S、M、H、D（MIDNIGHT）、W
    backupCount:存储拆分文件个数
    '''
    log_file = os.path.join(log_path,filename)
    logging.basicConfig(level=logging.DEBUG,format=message_format)

    log = logging.getLogger(filename) #定义对应程序模块名，默认root

    if not log.handlers:
        file =logging.handlers.TimedRotatingFileHandler(log_file,when=when,interval=1,backupCount=backupCount,encoding='utf-8')
        file.setFormatter(logging.Formatter(message_format))
        log.addHandler(file)
    return log


def getFileSizeLog(filename="my-size.log",filesize=100*1024*1024,backupCount=30):
    '''
    获取日志对象，文件大小超过fileSize大小拆分文件

    filename:日志文件名，默认my.log
    filesize:单个日志文件最大值，单位是bytes，默认100*1024*1024=100M，重命名文件名为my.log.1
    backupCount:存储拆分文件个数
    '''
    log_file = os.path.join(log_path,filename,format=message_format)
    logging.basicConfig(level=logging.DEBUG)

    log = logging.getLogger(filename) #定义对应程序模块名，默认root

    #定义过滤条件
    if not log.handlers:
        file=logging.handlers.RotatingFileHandler(log_file,maxBytes=filesize,backupCount=backupCount,encoding='utf-8')
        file.setFormatter(logging.Formatter(message_format))
        log.addHandler(file)
    return log
